package com.whpost.service.service.t;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TMenuDao;
import com.whpost.service.dao.t.TPermissionDao;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TMenu;
import com.whpost.service.entity.t.TPermission;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.NoSuchPaddingException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TMenuServices extends BaseServices {

    @Resource
    private TMenuDao tMenuDao;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private TPermissionServices tPermissionServices;
    @Resource
    private TPermissionDao tPermissionDao;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cdmc="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cdmc")) {
                cdmc = jsonObject.getString("cdmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TMenu> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TMenu> TMenuListInfo = new ListInfo<>();
            QueryWrapper<TMenu> tMenuQueryWrapper = new QueryWrapper<TMenu>();
            if (!StringUtils.isEmpty(cdmc)){
                tMenuQueryWrapper.like("name",cdmc);
            }else{
                tMenuQueryWrapper.eq("1","1");
            }
            tMenuQueryWrapper.orderByAsc("xh");

            IPage<TMenu> TMenuIPage = tMenuDao.getTMenuTreeTable(page,tMenuQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(TMenuIPage.getTotal());
            pageInfo.setCurPage(TMenuIPage.getCurrent());
            pageInfo.setPageSize(TMenuIPage.getSize());
            pageInfo.setPageTotal(TMenuIPage.getPages());

            TMenuListInfo.setPageInfo(pageInfo);
            TMenuListInfo.setListInfo(TMenuIPage.getRecords());

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",TMenuListInfo);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo tree(String loginId,Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            Map<String,Object> rtnMap = new HashMap<>();
            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TMenu tMenu = new TMenu();
            TMenu tMenuSon = new TMenu();
            String treejson="";
            //一级菜单
            List<TMenu> tMenuList = new ArrayList<>();
            tMenuList = tMenuDao.selectList(new QueryWrapper<TMenu>().eq("jb","1").orderByAsc("xh"));

            //二级菜单
            List<TMenu> tMenuListSon = new ArrayList<>();
            for (int i=0;i<tMenuList.size();i++){
                tMenu = new TMenu();
                tMenu = tMenuList.get(i);
                treejson += "{id:\""+tMenu.getId()+"\",name: \""+tMenu.getName()+"\",dz:\"info?lx=1&id="+tMenu.getId()+"\"},";
                //放入二级菜单
                tMenuListSon = new ArrayList<>();
                tMenuListSon = tMenuDao.selectList(new QueryWrapper<TMenu>().eq("pid",tMenu.getId()).orderByAsc("xh"));
                for (int k=0;k<tMenuListSon.size();k++){
                    tMenuSon = new TMenu();
                    tMenuSon = tMenuListSon.get(k);
                    treejson += "{id:\""+tMenuSon.getId()+"\",pId:\""+tMenuSon.getPid()+"\", name: \""+tMenuSon.getName()+"\",dz:\"info?lx=1&id="+tMenuSon.getId()+"\"},";
                }
            }
            rtnMap.put("treejson", JSON.parse("["+treejson+"]"));
            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",pid="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }
            Map<String,Object> rtnMap = new HashMap<>();

            if ("1".equals(lx)){
                TMenu tMenu = new TMenu();
                tMenu = tMenuDao.getTMenuById(id);
                rtnMap.put("tMenu",tMenu);
            }
            if (!StringUtils.isEmpty(pid)){
                TMenu pMenu = new TMenu();
                pMenu = tMenuDao.getTMenuById(pid);
                if (null==pMenu){
                    return new ResultInfo(500,"上级菜单信息丢失！",null);
                }
                rtnMap.put("pMenu",pMenu);
            }
            //一级菜单
            List<TMenu> tMenuList = new ArrayList<>();
            tMenuList = tMenuDao.selectList(new QueryWrapper<TMenu>().eq("jb","1").orderByAsc("xh"));
            rtnMap.put("tMenuList",tMenuList);

            ResultInfo resultInfo = new ResultInfo(0, "查询成功！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",cdmc="",link="",xsxh="",tbmc="",qxdm="",pid="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("cdmc")) {
                cdmc = jsonObject.getString("cdmc");
            }
            if (jsonObject.containsKey("link")) {
                link = jsonObject.getString("link");
            }
            if (jsonObject.containsKey("xsxh")) {
                xsxh = jsonObject.getString("xsxh");
            }
            if (jsonObject.containsKey("tbmc")) {
                tbmc = jsonObject.getString("tbmc");
            }
            if (jsonObject.containsKey("qxdm")) {
                qxdm = jsonObject.getString("qxdm");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }

            if (StringUtils.isEmpty(cdmc)){
                ResultInfo resultInfo = new ResultInfo(500, "菜单名称不能为空！",null);
                return backRtn(resultInfo,loginId);
            }

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"menu.addDo");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TMenu tMenu = new TMenu();
            if ("1".equals(lx)){
                tMenu = tMenuDao.selectById(id);
            }
            tMenu.setName(cdmc);
            tMenu.setZjm(ToolBean.getPy(cdmc));
            ToolBean.info("pid:"+pid);
            //新增的才可能是级别为2
            if (!StringUtils.isEmpty(pid)){
                tMenu.setPid(Long.valueOf(pid));
                tMenu.setJb(2L);
            }else{
                //如果是修改，不改变级别，如果是新增，则都是第一级
                if ("0".equals(lx)) tMenu.setJb(1L);
            }
            tMenu.setIco(tbmc);
            tMenu.setHref(link);
            if (!StringUtils.isEmpty(xsxh)) tMenu.setXh(Long.valueOf(xsxh));
            ResultInfo resultInfo;
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",cdmc);
            if ("1".equals(lx)){
                tMenu.setQxdm(qxdm);
                tMenuDao.updateById(tMenu);
                if (!StringUtils.isEmpty(qxdm)){
                    tPermissionServices.addPermission(tMenu);
                }
                if (StringUtils.isEmpty(pid) && tMenu.getJb()==2) tMenuDao.setPidNull(id);
                resultInfo = new ResultInfo(2, "修改成功！",rtnMap);
            }else{
                tMenu.setQxdm(qxdm);
                tMenuDao.insert(tMenu);
                if (!StringUtils.isEmpty(qxdm)){
                    tPermissionServices.addPermission(tMenu);
                }
                resultInfo = new ResultInfo(1, "新增成功！",rtnMap);
            }
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo qy(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String id="",new_pid="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("new_pid")) {
                new_pid = jsonObject.getString("new_pid");
            }

            if (StringUtils.isEmpty(new_pid)){
                ResultInfo resultInfo = new ResultInfo(500, "新上级名称不能为空！",null);
                return backRtn(resultInfo,loginId);
            }

            if (StringUtils.isEmpty(id)){
                ResultInfo resultInfo = new ResultInfo(500, "关键参数丢失！",null);
                return backRtn(resultInfo,loginId);
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TMenu tMenu;
            tMenu = tMenuDao.selectById(id);
            tMenu.setPid(Long.parseLong(new_pid));
            tMenuDao.updateById(tMenu);
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",tMenu.getName());
            return backRtn(new ResultInfo(1, "迁移成功！",rtnMap),loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String menu_id="";
            if (jsonObject.containsKey("id")) {
                menu_id = jsonObject.getString("id");
            }
            if (StringUtils.isEmpty(menu_id)){
                ResultInfo resultInfo = new ResultInfo(500, "没有需要删除的信息！",null);
                return backRtn(resultInfo,loginId);
            }
            int sl = tMenuDao.countSon(Long.parseLong(menu_id.trim()));
            if (sl>=1){
                ResultInfo resultInfo = new ResultInfo(500, "请先删除下级数据！",null);
                return backRtn(resultInfo,loginId);
            }else {
                tMenuDao.deleteById(menu_id);
                tPermissionDao.delete(new QueryWrapper<TPermission>().eq("menu_id",menu_id));
                ResultInfo resultInfo = new ResultInfo(3, "删除成功！",null);
                return backRtn(resultInfo,loginId);
            }
        }
    }
}
